package com.example.pcl.controller;

import com.example.pcl.constant.MessageConstants;
import com.example.pcl.constant.StatusCodeConstants;
import com.example.pcl.result.Result;
import com.example.pcl.utils.AliOssUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
@RequiredArgsConstructor
@Tag(name = "通用相关接口")
public class CommonController {

    private final AliOssUtil aliOssUtil;

    /**
     * 文件上传
     * @param file 文件
     * @return URL
     */
    @PostMapping("/admin/upload")
    @Operation(summary = "文件上传", description = "管理员文件上传接口")
    public Result<?> upload(MultipartFile file) {
        log.info("文件上传:{}", file);

        String filename = file.getOriginalFilename();
        if (!StringUtils.isBlank(filename)) {
            try {
                String s = filename.substring(filename.lastIndexOf("."));
                return Result.success(aliOssUtil.upload(file.getBytes(), UUID.randomUUID() + s), MessageConstants.OPERATION_SUCCESSFUL);
            } catch (IOException e) {
                log.error("文件上传失败:{}", e.toString());
            }
        }
        return Result.error(StatusCodeConstants.BAD_REQUEST, MessageConstants.UNKNOWN_ERROR);
    }

    /**
     * 文件上传
     * @param file 文件
     * @return URL
     */
    @PostMapping("/user/upload")
    @Operation(summary = "文件上传", description = "用户文件上传接口")
    public Result<?> upload2(MultipartFile file) {
        return this.upload(file);
    }
}
